/**
 * @param {character[][]} board
 * @param {number[]} click
 * @return {character[][]}
 */
var updateBoard = function (board, click) {

  function isValid(i, j) {
    if (i >= 0 && i < board.length && j >= 0 && j < board[0].length) {
      return true;
    } else {
      return false;
    }
  }

  function isClickBom(i, j) {
    return isValid(i, j) && board[i][j] == 'M';
  }

  function isClickEmpty(i, j) {
    if (isClickBom(i + 1, j) || isClickBom(i - 1, j) || isClickBom(i, j + 1) ||
      isClickBom(i, j - 1) || isClickBom(i + 1, j + 1) || isClickBom(i - 1, j - 1) ||
      isClickBom(i + 1, j - 1) || isClickBom(i - 1, j + 1)) {
      return false;
    } else {
      return true;
    }
  }

  function clickNumber(i, j) {
    let count = 0;
    if (isClickBom(i + 1, j)) count++;
    if (isClickBom(i - 1, j)) count++;
    if (isClickBom(i, j + 1)) count++;
    if (isClickBom(i, j - 1)) count++;
    if (isClickBom(i + 1, j + 1)) count++;
    if (isClickBom(i - 1, j - 1)) count++;
    if (isClickBom(i + 1, j - 1)) count++;
    if (isClickBom(i - 1, j + 1)) count++;
    board[i][j] = "" + count + "";
    return;
  }

  function isClicked(i, j) {
    return board[i][j] == 'B';
  }

  function dfs(i, j) {
    if (!isValid(i, j)|| isClickBom(i, j) || isClicked(i, j)) return;
    if (isClickEmpty(i, j)) {
      board[i][j] = "B";
      dfs(i + 1, j);
      dfs(i - 1, j);
      dfs(i, j + 1);
      dfs(i, j - 1);
      dfs(i + 1, j + 1);
      dfs(i - 1, j - 1);
      dfs(i + 1, j - 1);
      dfs(i - 1, j + 1);
    } else {
      clickNumber(i, j);
    }
  }
  let indexI = click[0],
    indexJ = click[1];

  if (isClickBom(indexI, indexJ)) {
    board[indexI][indexJ] = 'X';
  } else if (!isClickEmpty(indexI, indexJ)) {
    clickNumber(indexI, indexJ);
  } else {
    dfs(indexI, indexJ);
  }
  return board;

};
let board = [
    ["E", "E", "E", "E", "E"],
    ["E", "E", "M", "E", "E"],
    ["E", "E", "E", "E", "E"],
    ["E", "E", "E", "E", "E"]
  ],
  click = [3, 0];
console.log(updateBoard(board, click));
board = [["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]], click = [1,2];
console.log(updateBoard(board, click));
